
require_relative 'job'

module CSDNConfig

	class CSDNProject < Struct.new(:continuous, :release, :coverage)

		def initialize(name)
			self.continuous = CSDNConfig::Job.new("#{name}-master-continuous")
			self.release = CSDNConfig::Job.new("#{name}-master-release")
			self.coverage = CSDNConfig::Job.new("#{name}-master-coverage")

			@all = [self.continuous, self.release, self.coverage]

			all.repo_name = name
			setup_defaults

			yield self if block_given?
		end

		def setup_defaults

			all.add_permission 'core', :all

			continuous.triggers << CSDNConfig::Triggers::SCM.frequently

			#continuous.add_dependency '' -> in case the project need to depend on a common project
			continuous.command = CSDNConfig::Command.new do |cmd|
				cmd.standard_build_setup
				cmd.save_build_number '$WORKSPACE/jenkins_build.txt'
				cmd.clean_build_directory 'target'
				cmd.make
				cmd.puts
			end
			
			#Not need to apply a tag on the Continuous Build
			#continuous.post_build << CSDNConfig::PostBuild::CreateGitTag.new('jenkins-$BUILD_NUMBER', 'Tagging continuous build')
			continuous.post_build << CSDNConfig::PostBuild::Artifacts.new('jenkins_build.txt')
			#continuous.post_build << CSDNConfig::PostBuild::CleanWorkspace.new

			release.add_dependency continuous.name
			release.pre_build << CSDNConfig::PreBuild::CopyArtifacts.new(from: continuous.name, filter: 'jenkins_build.txt')
			release.command = CSDNConfig::Command.new do |cmd|
				cmd.standard_build_setup
				cmd.checkout_tag '$WORKSPACE/src', '$WORKSPACE/jenkins_build.txt'
				cmd.clean_build_directory 'target'
				cmd.make
				cmd.package
				cmd.puts
			end
			#release.post_build << CSDNConfig::PostBuild::FTPUpload.new('$WORKSPACE/build/*.rpm')
			release.post_build << CSDNConfig::PostBuild::CleanWorkspace.new

			coverage.add_dependency continuous.name
			#coverage.node_tags += %w{gcovr}
			coverage.command = CSDNConfig::Command.new do |cmd|
				#cmd.standard_build_setup
				#cmd.clean_build_directory 'target'
				#cmd.make
				#cmd.popd
				#disable the coverage report now
				#cmd.gcovr_coverage_report 'src', 'build'
			end
			#coverage.post_build << CSDNConfig::PostBuild::Artifacts.new('coverage_report.xml')
			#coverage.post_build << CSDNConfig::PostBuild::CodeCoverageReport.new('coverage_report.xml')
			#coverage.post_build << CSDNConfig::PostBuild::CleanWorkspace.new
		end

		def all
			ConfigMultiplexer.new(*@all)
		end

		def each(&block)
			return to_enum unless block_given?
			@all.each(&block)
		end


		class ConfigMultiplexer
			def initialize(*configs)
				@configs = configs
			end

			def method_missing(method,*args,&block)
				@configs.each do |config|
					config.send(method,*args,&block)
				end
			end
		end

	end

end
